// battle.js

var selectCharacterId = null; // 存储选中的角色ID

document.addEventListener('DOMContentLoaded', () => {
    arrangeCards()
    // 初始化游戏
    initGame();
    // 添加事件监听器
    setupEventListeners();
});

async function initGame() {
    // 初始化游戏状态
    console.log("游戏初始化...");
    // 获取当前模式
    const currentMode = window.location.search.split('=')[1];
    // 初始化游戏数据
    await initLevel(currentMode);
    // 初始化手牌布局
    await arrangeCards();
}

async function initLevel(currentMode) {
    // 关卡模式初始化
    console.log("关卡模式初始化...");
    // 获取当前关卡
    fetch('/api/game/progress')
        .then(response => response.json())
        .then(data => {
            const currentLevel = data.level;
            document.getElementById('currentLevel').textContent = currentLevel;
            console.log(`当前关卡: ${currentLevel}`);
        })
        .catch(error => {
            console.error('获取进度失败:', error);
        });
    // 更新游戏状态
    await updateGameState();
}

async function setupEventListeners() {
    // 投降按钮点击事件
    document.getElementById('surrenderBtn').addEventListener('click', () => {
        if (confirm('确定要投降吗？')) {
            surrenderGame();
        }
    });

    // 回合结束按钮点击事件
    document.getElementById('nextTurnBtn').addEventListener('click', async () => {
        await showRoundSwitch('我方回合结束');
        await new Promise(resolve => setTimeout(resolve, 300));
        const isEnd = await endTurn();
        console.log(isEnd);
        if (isEnd) {
            console.log('游戏结束');
            return;
        }
        // 为所有field-character添加attacking动画
        const fieldCharacters = document.querySelectorAll('.field-character');
        if (fieldCharacters && fieldCharacters.length > 0) {
            fieldCharacters.forEach(char => {
                char.classList.add('attacking');
            });
        }
        // 等待所有changing动画结束
        const changingHps = document.querySelectorAll('.char-hp.changing');
        if (changingHps && changingHps.length > 0) {
            await waitForAnimationEnd(changingHps[0]);
        }
        await new Promise(resolve => setTimeout(resolve, 300));
        await showRoundSwitch('我方回合开始');
    });
    
    // 我方手牌点击事件
    document.querySelector('.player-card-area .hand-area').addEventListener('click', async (e) => {
        const card = e.target.closest('.card');
        if (card && !card.classList.contains('card-back')) {
            const cardId = parseInt(card.dataset.id);
            console.log(`打出卡牌: ${cardId}`);
            const result = await playCard(cardId, selectCharacterId);
            if (result) {
                card.classList.add('playing');
                setTimeout(async () => {
                    await updateGameState();
                    await arrangeCards();
                }, 500);
            }
        }
    });
    
    // 场上角色点击事件
    document.querySelectorAll('.battlefield .field-character').forEach(async char => {
        char.addEventListener('click', async () => {
            const characterId = parseInt(char.dataset.id);
            console.log(`选择角色: ${characterId}`);
            await selectCharacter(characterId);
            await arrangeCards();
        });
    });

    // 使用技能
    document.getElementById('playerSkill').addEventListener('click', async () => {
        console.log(`使用技能`);
        await useSkill();
        await updateGameState();
        await arrangeCards();
    });
    
}

async function useSkill() {
    console.log(`使用技能`);
    // 模拟API调用
    const response = await fetch('/api/battle/use-skill');
    const data = await response.json();
    console.log(`使用技能结果: ${data}`);
    if (data.success) {
        console.log(`使用技能成功`);
        document.getElementById('playerSkill').classList.add('skill-effect');
        await waitForAnimationEnd(document.getElementById('playerSkill'));
    } else {
        console.error('使用技能失败:', data.message);
    }
}

async function dealCards() {
    // 发牌
    const response = await fetch('/api/battle/deal-cards');
    const data = await response.json();
    console.log(`发牌结果: ${data}`);
    if (data.success) {
        console.log(`发牌成功`);
    } else {
        console.error('发牌失败:', data.message);
    }
}

async function selectCharacter(characterId) {
    try {
        // 模拟API调用
        selectCharacterId = characterId;
        document.getElementById('currentSelectCharacter').textContent = characterId || 0;
        console.log(`选择角色: ${characterId}`);
    } catch (error) {
        console.error('选择角色失败:', error);
    }
}

async function endTurn() {
    const response = await fetch('/api/battle/end-turn');
    const data = await response.json();
    if (data.success) {
        console.log(`回合结束`);
        console.log(data.battleResult);
        if (data.battleResult.isEnd) {
            console.log(data.battleResult.isVictory);
            console.log(data.battleResult.rewards.gold);
            showBattleResult(data.battleResult.isVictory, data.battleResult.rewards.gold);
            return true;
        } else {
            await dealCards();
            await updateGameState();
            await arrangeCards();
            return false;
        }
    } else {
        console.error('回合结束失败:', data.message);
        return false;
    }
}

async function playCard(cardId, targetId = null) {
    try {
        // 模拟API调用
        console.log(`尝试打出卡牌 ${cardId} 到目标 ${targetId}`);
        
        // 这里应该是实际的API调用
        const response = await fetch('/api/battle/play-card', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                cardId: cardId,
                targetId: targetId
            })
        });
        
        const result = await response.json();
        if (result.success) {
            return true;
        } else {
            console.error('打出卡牌失败:', result.message);
            alert(result.message);
            return false;
        }
        
    } catch (error) {
        console.error('打出卡牌失败:', error);
        alert(error.message);
        return false;
    }
}

async function surrenderGame() {
    try {
        console.log("玩家选择投降...");
        
        // 这里应该是实际的API调用
        const response = await fetch('/api/battle/clear-battle');
        
        const result = await response.json();
        if (result.success) {
            showBattleResult(false);
        } else {
            console.error('投降失败:', result.message);
        }
        
        // 模拟投降成功
        setTimeout(() => {
            showBattleResult(false);
        }, 1000);
        
    } catch (error) {
        console.error('投降失败:', error);
    }
}

async function showRoundSwitch(content) {
    const overlay = document.getElementById('roundEndOverlay');
    overlay.style.display = 'flex';
    overlay.querySelector('.round-end-title').textContent = content;
    overlay.addEventListener('animationend', () => {
        overlay.style.display = 'none';
    });
    await waitForAnimationEnd(overlay);
}

function showBattleResult(isVictory, rewardGold=0) {
    const resultOverlay = document.getElementById('settlementOverlay');
    const title = resultOverlay.querySelector('.settlement-title');
    const reward = resultOverlay.querySelector('.reward-amount');
    
    // 更新结算界面
    title.textContent = isVictory ? '战斗胜利！' : '战斗失败！';
    title.className = isVictory ? 'settlement-title victory' : 'settlement-title defeat';
    reward.textContent = rewardGold;
    
    // 显示结算界面
    resultOverlay.style.display = 'flex';
    
    // 添加点击继续的事件
    resultOverlay.onclick = () => {
        resultOverlay.style.display = 'none';
        // 这里可以添加返回或继续的逻辑
        window.location.href = '/';
        console.log("返回主菜单...");
    };
}

// 更新主要角色信息
function updateMainRoleInfo(playerAvatar, playerStats, playerSkill, playerWeapon, mainRole) {
    if (playerAvatar && playerStats && playerSkill && playerWeapon && mainRole) {
        // 更新玩家头像
        playerAvatar.src = mainRole.imageUrl;
        playerAvatar.alt = mainRole.name;
        playerAvatar.title = mainRole.name; 
        // 更新玩家信息
        playerStats.innerHTML = `
            <p>${mainRole.introduction}</p>
            <p>生命值: ${mainRole.currentHp}/${mainRole.maxHp}</p>
            <p>法力值: ${mainRole.currentMp}/${mainRole.maxMp}</p>
        `;
        // 更新玩家技能
        playerSkill.src = mainRole.skill.imageUrl;
        playerSkill.alt = mainRole.skill.name;
        playerSkill.title = mainRole.skill.introduction;
        if (playerSkill.classList.contains('skill-effect')) {
            playerSkill.classList.remove('skill-effect');
        }
        // 更新玩家武器
        if (mainRole.weapon) {
            playerWeapon.innerHTML = `
                <img src="${mainRole.weapon.imageUrl}" alt="${mainRole.weapon.name}" title="${mainRole.weapon.introduction}">
            `
        } else {
            playerWeapon.innerHTML = '';
        }
    }
}

// 更新在场角色信息
function updateFieldRoleInfo(playerField, appearRoles) {
    if (playerField && appearRoles) {
        // 更新玩家在场角色
        const roleFields = []
        appearRoles.forEach(role => {
            console.log(role);
            let playerWeapon = '';
            let attack = role.currentAttack;
            let maxHp = role.maxHP;
            if (role.weapon) {
                playerWeapon = `
                    <img src="${role.weapon.imageUrl}" alt="${role.weapon.name}" title="${role.weapon.introduction}">
                `;
            }
            
            let playerBuffs = [];
            if (role.buffs) {
                playerBuffs = role.buffs.map(buff => {
                    return `
                            <div class="role-buff-slot" id="roleBuff">
                                <img src="${buff.imageUrl || "images/战士卡.png"}" title="${buff.introduction}\n效果: ${buff.buffValue}\n持续时间: ${buff.duration}/${buff.buffDuration}" alt="buff">
                            </div>
                    `;
                });
            }
            let playerDeBuffs = []
            if (role.deBuffs) {
                playerDeBuffs = role.deBuffs.map(deBuff => {
                    return `
                            <div class="role-buff-slot" id="roleBuff">
                                <img src="${deBuff.imageUrl || "images/战士卡.png"}" title="${deBuff.introduction}\n持续时间: ${deBuff.duration}/${deBuff.deBuffDuration}" alt="deBuff">
                            </div>
                    `; 
                }) 
            }

            const entering = role.isFirstShow ? 'entering' : '';
            const hurt = role.isHurt ? 'changing' : '';
            const roleField = `
                <div class="field-character ${entering}" data-id="${role.id}" onclick="selectCharacter(${role.id})">
                    <img class="field-character-image" src="${role.imageUrl}" alt="${role.name}" title="${role.introduction}">
                    <div class="field-character-content">
                        <div class="char-attack">攻击: ${attack}</div>
                        <div class="char-hp ${hurt}">HP: ${role.currentHp}/${maxHp}</div>
                        <div class="char-name">${role.name}</div>
                    </div>
                    <div class="role-equipment-area">
                        <div class="role-equipment-slot" id="roleWeapon">
                            ${playerWeapon}
                        </div>
                        <div class="role-buff-area">
                            ${playerBuffs.join('')}
                            ${playerDeBuffs.join('')}
                        </div>
                    </div>
                </div>
                `;
            roleFields.push(roleField);
        });
        playerField.innerHTML = roleFields.join('');
    }
}

async function updateGameState() {
    // 获取当前信息
    let state = null;
    const response = await fetch('/api/battle/battle-state');
    const data = await response.json();
    console.log(`当前信息: ${data}`);
    state = data;
    // 更新全局信息
    const currentTurn = document.getElementById('currentTurn');
    if (currentTurn && state.globalInfo && state.globalInfo.currentTurn) {
        currentTurn.textContent = state.globalInfo.currentTurn;
    }

    // 更新玩家信息
    if (state.playerInfo) {
        const playerStats = document.querySelector('.player-area .character-stats');
        const playerAvatar = document.getElementById('playerAvatar');
        const playerSkill = document.getElementById('playerSkill');
        const playerWeapon = document.getElementById('playerWeapon');
        // 更新主要角色信息
        updateMainRoleInfo(playerAvatar, playerStats, playerSkill, playerWeapon, state.playerInfo.mainRole);

        // 更新玩家在场角色
        const playerField = document.querySelector('.player-card-area .battlefield');
        updateFieldRoleInfo(playerField, state.playerInfo.appearRoles);
        
        const playerHand = document.querySelector('.player-card-area .hand-area');
        console.log(`玩家手牌: ${state.playerInfo.handCards}`);
        if (playerHand && state.playerInfo.handCards) {
            playerHand.innerHTML = state.playerInfo.handCards.map(card => {
                const color = card.cost <= state.playerInfo.mainRole.currentMp ? '#ffd700' : '#e74c3c';
                return `
                    <div class="player-card card" style="--mana-color: ${color}" data-id="${card.id}" title="${card.introduction}">
                        <div class="card-cost" style="--mana-color: ${color}">${card.cost}</div>
                    <img class="card-image" src="${card.imageUrl || 'https://via.placeholder.com/70x60?text=卡牌'}" alt="${card.name}">
                        <div class="card-name">${card.name}</div>
                    </div>
                `;
            }).join('');
        }
    }
    
    // 更新敌方信息
    if (state.enemyInfo) {
        // 更新敌方主要角色信息
        const enemyStats = document.querySelector('.enemy-area .character-stats');
        const enemyAvatar = document.getElementById('enemyAvatar');
        const enemySkill = document.getElementById('enemySkill');
        const enemyWeapon = document.getElementById('enemyWeapon');
        updateMainRoleInfo(enemyAvatar, enemyStats, enemySkill, enemyWeapon, state.enemyInfo.mainRole);
        
        // 更新敌方在场角色
        const enemyField = document.querySelector('.enemy-card-area .battlefield');
        updateFieldRoleInfo(enemyField, state.enemyInfo.appearRoles);
        
        const enemyHand = document.querySelector('.enemy-card-area .hand-area');
        if (enemyHand && state.enemyInfo.handCardSize) {
            enemyHand.innerHTML = Array.from({length: state.enemyInfo.handCardSize}).map((_, index) => `
                    <div class="enemy-card card" data-id="${index + 1}">
                        <img class="enemy-card-image" src="images/deck-cover.png">
                    </div>
            `).join('');
        }
    }
}

// 动态计算手牌位置
async function arrangeCards() {
    const handAreas = document.querySelectorAll('.fan-hand');
    handAreas.forEach(hand => {
        const cards = hand.querySelectorAll('.card');
        const total = cards.length;
        // 根据卡牌数量动态调整最大展开角度
        const maxPercent = total * 30;
        
        cards.forEach((card, index) => {
            if (total === 1) {
                card.style.setProperty('--offset', `-50%`);
            } else {
                const offset = (index - (total-1)/2) * (maxPercent*2/(total-1)) - 50;
                card.style.setProperty('--offset', `${offset}%`);
            }
        });
    });
}

function waitForAnimationEnd(element) {
    return new Promise((resolve) => {
        element.addEventListener('animationend', resolve, { once: true });
    });
}